<template>
  <view class="container">
    <!-- 标题 -->
    <text class="title">注册</text>
    <!-- 头像上传 -->
    <view class="avatar-container">
      <image v-if="avatarUrl" :src="avatarUrl" class="avatar" mode="aspectFill"></image>
      <view v-else class="avatar-placeholder">
        <text>上传头像</text>
      </view>
      <button class="upload-btn" size="mini" @click="chooseImage">选择头像</button>
    </view>
    <!-- 输入框 -->
    <view class="input-container">
      <view class="input-item">
        <text class="input-label">手机号</text>
        <input class="input" v-model="phone" placeholder="请输入手机号" />
      </view>
      <view class="input-item code-item">
        <text class="input-label">验证码</text>
        <input class="input code-input" v-model="code" placeholder="请输入验证码" />
        <button class="get-code-btn" :disabled="countdown > 0" @click="showCaptchaPopup">
          {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
        </button>
      </view>
      <view class="input-item">
        <text class="input-label">密码</text>
        <input class="input" v-model="password" placeholder="请输入密码" type="password" />
      </view>
      <view class="input-item">
        <text class="input-label">邮箱</text>
        <input class="input" v-model="email" placeholder="请输入邮箱" />
      </view>
      <view class="input-item">
        <text class="input-label">用户名</text>
        <input class="input" v-model="username" placeholder="请输入用户名" />
      </view>
      <view class="input-item">
        <text class="input-label">公司</text>
        <input class="input" v-model="company" placeholder="请输入公司/学校" />
      </view>
    </view>
    <!-- 注册按钮 -->
    <button class="register-btn" @click="handleRegister">注册</button>
    <!-- 登录链接 -->
    <text class="login-link" @click="goToLogin">已有账号？去登录</text>

    <!-- 图形验证码弹窗 -->
    <uni-popup ref="popup" type="dialog">
      <view class="captcha-modal">
        <view class="captcha-title">请输入图形验证码</view>
        <image class="captcha-image" :src="captchaImg" @click="initGraphCaptcha"></image>
        <input class="captcha-input" v-model="captcha" placeholder="请输入验证码" />
        <view class="captcha-btns">
          <button class="captcha-btn" @click="popup.close()">取消</button>
          <button class="captcha-btn confirm" @click="confirmCaptchaAndSend">确定</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { defineComponent, ref, onUnmounted } from 'vue';
import { register, getGraphCaptcha, sendSmsCode } from '@/api/login';

export default defineComponent({
  setup() {
    // 表单数据
    const phone = ref('');
    const password = ref('');
    const username = ref(''); // 注意：对应后端的name字段
    const company = ref('');
    const avatarUrl = ref('');
    const code = ref('');
	const email = ref('');
    // UI状态
    const countdown = ref(0);
    const popup = ref(null);
    const captchaImg = ref('');
    const captcha = ref('');
    const sendingCode = ref(false);
    const registering = ref(false);
    let timer = null;
	
	
	
	
    
    const chooseImage = () => {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'], 
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 直接使用本地临时路径，不上传
          avatarUrl.value = res.tempFilePaths[0];
          uni.showToast({ title: '已选择头像', icon: 'none' });
        },
        fail: () => {
          uni.showToast({ title: '选择头像失败', icon: 'none' }); 
        }
      });
    };


    // 验证码相关
    const initGraphCaptcha = async () => {
      try {
        const imgData = await getGraphCaptcha();
        captchaImg.value = imgData;
      } catch (error) {
        uni.showToast({ title: '获取验证码失败', icon: 'none' });
      }
    };

    const showCaptchaPopup = async () => {
      if (!/^1[3-9]\d{9}$/.test(phone.value)) {
        return uni.showToast({ title: '请输入正确手机号', icon: 'none' });
      }
      await initGraphCaptcha();
      popup.value.open();
    };

    const confirmCaptchaAndSend = async () => {
      if (!captcha.value) {
        return uni.showToast({ title: '请输入图形验证码', icon: 'none' });
      }

      sendingCode.value = true;
      try {
        await sendSmsCode(phone.value, captcha.value);
        popup.value.close();
        startCountdown();
        uni.showToast({ title: '验证码已发送', icon: 'none' });
      } catch (error) {
        uni.showToast({
          title: error.message || '验证码发送失败',
          icon: 'none'
        });
        initGraphCaptcha();
      } finally {
        sendingCode.value = false;
      }
    };

    const startCountdown = () => {
      countdown.value = 60;
      timer = setInterval(() => {
        if (countdown.value <= 0) clearInterval(timer);
        else countdown.value--;
      }, 1000);
    };

    // 核心注册逻辑
    // 修改后的注册API调用
    const handleRegister = async () => {
      // 基础验证
      if (!/^1[3-9]\d{9}$/.test(phone.value)) {
        return uni.showToast({ title: '请输入正确手机号', icon: 'none' });
      }
      if (!password.value || password.value.length < 6) {
        return uni.showToast({ title: '密码需≥6位', icon: 'none' });
      }
      if (!username.value) {
        return uni.showToast({ title: '请输入姓名', icon: 'none' });
      }
      if (!code.value) {
        return uni.showToast({ title: '请输入验证码', icon: 'none' });
      }
    
      registering.value = true;
      try {
        // 修改后的参数传递
        const res = await register(
          phone.value,
          password.value,
          '', // 邮箱参数(后端不需要)
          username.value, // 对应后端的name
          company.value,
          avatarUrl.value,
          code.value,
          '' // post参数(可为空)
        );
		console.log("【注册响应】", res); // 打印完整响应
        // 更宽松的响应判断
        if (res && (res.code === 200 || res.success)) {
          uni.showToast({ title: '注册成功', icon: 'success' });
          setTimeout(() => uni.redirectTo({ url: '/pages/login/login' }), 1500);
        } else {
          throw new Error(res?.message || '注册失败');
        }
      } catch (error) {
        let msg = error.message;
        if (msg.includes('已存在')) msg = '该手机号已注册';
        else if (msg.includes('验证码')) msg = '验证码错误或已过期';
        uni.showToast({ title: msg, icon: 'none' });
      } finally {
        registering.value = false;
      }
    };


    // 其他方法
    const goToLogin = () => uni.redirectTo({ url: '/pages/login/login' });

    onUnmounted(() => timer && clearInterval(timer));

    return {
      phone,
      password,
      username,
      company,
	  email,
      avatarUrl,
      code,
      countdown,
      popup,
      captchaImg,
      captcha,
      sendingCode,
      registering,
      chooseImage,
      showCaptchaPopup,
      initGraphCaptcha,
      confirmCaptchaAndSend,
      handleRegister,
      goToLogin
    };
  }
});
</script>





<style>
.captcha-modal {
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  width: 80%;
  margin: 0 auto;
}

.captcha-title {
  text-align: center;
  font-size: 32rpx;
  margin-bottom: 30rpx;
}

.captcha-image {
  width: 250rpx;
  height: 80rpx;
  margin: 0 auto;
  display: block;
  margin-bottom: 30rpx;
}

.captcha-input {
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  padding: 0 20rpx;
  margin-bottom: 30rpx;
}

.captcha-btns {
  display: flex;
  justify-content: space-between;
}

.captcha-btn {
  flex: 1;
  margin: 0 10rpx;
}

.captcha-btn.confirm {
  background-color: #1aad19;
  color: #fff;
}
.captcha-container {
  display: flex;
  align-items: center;
  margin: 20rpx 0;
}
.captcha-img {
  width: 200rpx;
  height: 80rpx;
  margin-left: 20rpx;
}
.captcha-image {
  width: 150rpx;
  height: 60rpx;
  margin-left: 20rpx;
  border: 1rpx solid #eee;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 30px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  margin-bottom: 10px;
}

.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 10px;
  color: #999;
}

.upload-btn {
  background-color: #3AB54A;
  color: white;
}

.input-container {
  width: 95%;
}

.input-item {
  display: flex;
  align-items: center;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  margin-bottom: -1px;
  background-color: white;
  padding: 0 10px;
}

.code-item {
  position: relative;
}

.input-label {
  font-size: 14px;
  color: #333;
  width: 60px;
}

.input {
  flex: 1;
  height: 40px;
  border: none;
  font-size: 14px;
  padding-left: 10px;
}

.code-input {
  flex: none;
  width: 60%;
}

.get-code-btn {
  position: absolute;
  right: 10px;
  height: 30px;
  line-height: 30px;
  font-size: 12px;
  background-color: #3AB54A;
  color: white;
  border-radius: 4px;
}

.get-code-btn[disabled] {
  background-color: #ccc;
}

.input-item:first-child {
  border-top: 1px solid #ccc;
}

.input-item:last-child {
  border-bottom: 1px solid #ccc;
}

.register-btn {
  width: 60%;
  height: 40px;
  background-color: #3AB54A;
  color: white;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  margin-top: 40px;
}

.login-link {
  font-size: 12px;
  color: #3AB54A;
  margin-top: 20px;
}
</style>
